package com.apache.ius.listener;

import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.service.impl.redis.JedisSsoUtil;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.ius.IusSqlTools;
//import com.apache.ius.function.ScriptEngineUtil;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:启动加载IUS参数listener
 *
 * @author dyh 创建时间：2018年03月05日
 */
public class IusParamsListener implements ServletContextListener {

    private Logger log = Logger.getLogger(getClass());

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        new Thread(new SetIusParamsCache()).start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //
    }

    class SetIusParamsCache implements Runnable {

        private IDao iusPubDao;

        private CacheManager cacheManager;

        @Override
        public void run() {
            boolean mark = true;
            do{
                try {
                    if(null != SpringContextLoader.getContext()){
                        mark =false;
                        setIusParamsCache();
                        //setRulesProCache();
                    }else{
                        try {
                            Thread.sleep(2000l);
                        }catch (InterruptedException e){
                            ///
                        }
                    }
                } catch (Exception e) {
                    log.error("初始化IUS参数失败：", e);
                    System.exit(0);
                }
            }while(mark);
        }

        private void setIusParamsCache() {
            log.info("IUS接口参数-数据加载缓存！");
            long startTime = System.currentTimeMillis();
            String execSql = "select * from sys_param_manager";
            if (StrUtil.isNotNull(execSql)) {
                MethodParam params = new MethodParam("ByObjInfo", "", "", IusSqlTools.SPANCENAME);
                params.setParams("dyncSql", execSql);
                List list = getIusManager().select(params);
                if (!StrUtil.isEmpty(list)) {
                    int count = list.size();
                    for (int i = 0; i < count; i++) {
                        Map map = (Map) list.get(i);
                        String key = map.get("formName") + "_" + map.get("pageName");
                        setIusParamCache(key, map);
                    }
                    log.info("IUS接口参数-共计缓存加载(" + count + "条)，执行时间=" + (System.currentTimeMillis() - startTime)+"ms");
                } else {
                    log.error("没有获取到ParamManager信息");
                }
            }
        }

       /* private void setRulesProCache() {
            long startTime = System.currentTimeMillis();
            MethodParam mp = new MethodParam("ByObjInfo", "", "", IusSqlTools.SPANCENAME);
            StringBuilder execSql = new StringBuilder(
                    "select rules_pro_id,constant_type,constant_status,prod_id,sale_id,rules_no,order_no,formula_name,formula_cal,deal_type,param_no,param_unit,formula_src,formula_no from trs_rules_pro");
            mp.setParams("dyncSql", execSql.toString());
            List list = getIusManager().select(mp);
            if (StrUtil.isEmpty(list)) {
                return;
            }
            int count = list.size();
            Map<String, List> ml = new HashMap();
            for (int i = 0; i < count; i++) {
                Map<String, String> map = (Map) list.get(i);
                Map<String, String> paramKey = new HashMap();
                paramKey.put("type", map.get("constantType"));
                paramKey.put("status", map.get("constantStatus"));
                paramKey.put("proId", map.get("prod_id"));
                paramKey.put("saleId", map.get("saleId"));
                String cacheKey = ScriptEngineUtil.getInstance().getCacheKey(paramKey);
                List lt = ml.get(cacheKey);
                if (null == lt) {
                    lt = new ArrayList();
                }
                lt.add(map);
                ml.put(cacheKey, lt);
            }
            for (String key : ml.keySet()) {
                LoadCacheFactory.getInstance().getCacheManager("")
                        .createCacheObject(key, ml.get(key));
            }
            log.info("业务环节参数-规则公式缓存加载(" + count + "条)的时间=" + (System.currentTimeMillis()
                    - startTime));
        }*/

        private void setIusParamCache(String key, Map<String, String> params) {
            if (JedisSsoUtil.getInstance().isRedisCache()) {
                JedisSsoUtil.getInstance().setIusparamcache(key, params);
            } else {
                getCache().createCacheObject(key, params);
            }
        }

        private CacheManager getCache() {
            if (null == cacheManager) {
                cacheManager = LoadCacheFactory.getInstance().getCacheManager("iusparamcache");
            }
            return cacheManager;
        }

        private IDao getIusManager() {
            if (null == iusPubDao) {
                this.iusPubDao = (IDao) SpringContextLoader.getBean("iusPubDao");
            }
            return iusPubDao;
        }

    }

}
